package Pattern.FactoryPattern.dynamic;


import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * @author:MJS
 * @create: 2023-02-02-16:23
 * @description:
 */
public class cglibProxy implements MethodInterceptor {
    private Object target;

    public cglibProxy(Object target) {
        this.target = target;
    }

    /**
     *给目标对象创建一个代理对象
    * */
    public Object getProxyInstance(){
        //1、工具类
        Enhancer enhancer = new Enhancer();
        //2、设置父类
        enhancer.setSuperclass(target.getClass());
        //3、设置回调函数
        enhancer.setCallback(this);
        //4、创建子类（代理对象）
        return enhancer.create();
    }

    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        System.out.println("买房前准备");
        //执行目标对象的方法
        Object result = method.invoke(target, objects);
        System.out.println("买房后装修");
        return result;
    }
}
